const createError = require("http-errors");
const express = require("express");
require("express-async-errors");
const path = require("path");
const cookieParser = require("cookie-parser");
const logger = require("morgan");
const session = require("express-session");
const moment = require("moment");
const cors = require("cors");
// 引入 json-server
const jsonServer = require("json-server");
const jsonServerRouter = jsonServer.router("db.json");
const jsonServerMiddlewares = jsonServer.defaults();

const auth = require("./middlewares/auth");

const indexRouter = require("./routes/index");
const usersRouter = require("./routes/users");
const postsRouter = require("./routes/posts");
const filesRouter = require("./routes/files");

const app = express();

// 模板引擎相关设置
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "ejs");

// locals
app.locals.dateFormat = (date) => {
  return moment(date).format("YYYY-MM-DD HH:mm:ss");
};

app.use(cors());
app.use(logger("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, "public")));

// session
app.use(
  session({
    secret: "hello world",
    resave: false,
    saveUninitialized: true,
  })
);

app.use("/", indexRouter);
app.use("/users", usersRouter);
app.use("/posts", auth, postsRouter);
app.use("/files", auth, filesRouter);
app.use(jsonServerMiddlewares);
app.use("/api", jsonServerRouter);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get("env") === "development" ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render("error");
});

module.exports = app;
